package crivia.ecp.carry.html.table;

import crivia.ecp.carry.html.DO;
import crivia.ecp.common.ECR;
import crivia.ecp.exception.WrongDocumentObject;

public class TDCell extends DO {
	
	public TDCell(TableRow row){
		baseRow = row;
	}

	@Override
	protected String name() {
		return "td";
	}

	@Override
	protected String innerHTML() {
		return inner == null ? "" : ECR.ns(inner.toString());
	}
	
	@Override
	public String toString() {
		if (colSpan > 1){
			addAttr("colSpan", colSpan);
		}
		if (rowSpan > 1){
			addAttr("rowSpan", rowSpan);
		}
		if (getBaseTable().isCutLongWord()) {
			addStyle("white-space", "nowrap");
			addStyle("text-overflow", "ellipsis");
			addStyle("overflow", "hidden");
		}
		if (null!=getBaseTable().getBorderColor1px()
		&& !"".equals(getBaseTable().getBorderColor1px())){
			String[] bsks = {
					"border-top"
					,"border-bottom"
					,"border-left"
					,"border-right"
			};
			for (String k : bsks){
				if (getStyleMap().containsKey(k)){
					continue;
				}
				addStyle(k, "1px solid "+getBaseTable().getBorderColor1px());
			}
		}
		return super.toString();
	}
	
	private TableRow baseRow;
	public TableRow getBaseRow() {
		if (null == baseRow){
			throw new WrongDocumentObject("No Base Row.");
		}
		return baseRow;
	}
	public Table getBaseTable() {
		return getBaseRow().getBaseTable();
	}
	
	private Object inner;
	public Object getInner() {
		return inner;
	}
	@SuppressWarnings("unchecked")
	public <T> T getInner(Class<T> type) {
		return (T) inner;
	}
	public TDCell setInner(Object inner) {
		this.inner = inner;
		return this;
	}
	
	private int colSpan = 1;
	public int getColSpan(){
		return colSpan;
	}
	public TDCell setColSpan(int colSpan){
		int newCellSize = getBaseRow().cellSize();
		if (isShow()){
			newCellSize = newCellSize - this.colSpan + colSpan;
		}
		if (newCellSize > getBaseTable().getColGroup().size()
			&& getBaseTable().getColGroup().size() > 0){
			throw Exception_CellsOver("New Cell Size Is More Then Column Group Size.");
		}
		if (colSpan > 0){
			this.colSpan = colSpan;
		} else {
			this.colSpan = 1;
		}
		return this;
	}
	
	private int rowSpan = 1;
	public int getRowSpan() {
		return rowSpan;
	}
	public TDCell setRowSpan(int rowSpan) {
		if (rowSpan > 0){
			this.rowSpan = rowSpan;
		} else {
			this.rowSpan = 1;
		}
		return this;
	}
	
	public TDCell setSpan(int colSpan , int rowSpan){
		setColSpan(colSpan);
		setRowSpan(rowSpan);
		return this;
	}

}
